<?php
/**
 * @author Pham Van Diep
 * @date: 18/02/2014
 * @description: save update image
 */
// not login
// not perm ad

if(!isset($AppUI->id) ||
    !isset($_SESSION['club'])||
    (isset($_SESSION['club']) && ! isset($_SESSION['image']))||
    (($_SESSION['image']&1)<<2 == 0)){
    redirect(HOST_BACKEND);
}

// data input
$arrErr             = array();
$intImageId         = intval($_POST['id']);//$this->input->post('id');
$intClubId          = intval($_POST['clubid']);//$this->input->post('clubid');
$intType            = intval($_POST['type']);//$this->input->post('type');
$intSrcId           = intval($_POST['srcid']);//$this->input->post('srcid');

$arrInfo = $this->image->get($intImageId);
if($arrInfo == null) {
    array_push($arrErr,$arrLocale['id_not_found']);
}
$strName            = trim($this->input->post('name',null));
$intLen = strlen($strName);
if($intLen < VL_NAME_MINLENGTH || $intLen > VL_NAME_MAXLENGTH ) {
	array_push($arrErr,$arrLocale['name_range']);
}

$strShort           = trim($this->input->post('sshort',null));
$intLen = strlen($strShort);
if($intLen < VL_SHORT_MINLENGTH || $intLen > VL_SHORT_MAXLENGTH ) {
	array_push($arrErr,$arrLocale['short_condition']);
}

$strDescription      = trim($this->input->post('description',null));
$intLen = strlen($strDescription);
if($intLen < VL_CONTENT_MINLENGTH ) {
	array_push($arrErr,$arrLocale['description_minlength']);
}

$strTag             = $this->input->post('tag',null);

if( $_FILES['file']['error'] == 0 ) {
    $this->load->library('upload');
    $info = $this->upload->do_upload('file');    
    if (count($info) == 0) {
        array_push($arrErr,$arrLocale['upload_failed']);
    }
}
if(isset($arrErr) && count($arrErr) == 0) {//allow save  
    if(isset($info)) {        
        $strPath  = $info['path'];
        $strImage = $info['realname'];
        $cFormat  = $info['extension'];
        $dblWidth = $info['width'];
        $dblHeight= $info['height']; 
    }else{
        $strPath  = $arrInfo->path;
        $strImage = $arrInfo->image;
        $cFormat  = $arrInfo->format;
        $dblWidth = $arrInfo->width;
        $dblHeight= $arrInfo->height; 
    }           
    $ret = $this->image->update($AppUI->id,$intImageId,$intClubId,$intSrcId,$intType,$strName,$strTag, $strShort,$strDescription,$strPath, $strImage, $cFormat, $dblWidth, $dblHeight );
    if($ret == -1 ) {
        array_push($arrErr,'image update faile');
        $_SESSION['IMAGE_ERROR'] = $arrErr;    
         redirect(HOST_BACKEND . 'image/edit?id=' . $intImageId );
    }else{
        if(isset($_SESSION['IMAGE_ERROR'])) unset($_SESSION['IMAGE_ERROR']);
    }
}
// occur error

if (isset($arrErr) && count($arrErr) > 0) { 
    $_SESSION['IMAGE_ERROR'] = $arrErr;    
   redirect(HOST_BACKEND . 'image/edit?id=' . $intImageId );
}
redirect(isset($_SESSION[SESSION_BACKURL]) ? $_SESSION[SESSION_BACKURL] : HOST_BACKEND);
